package com.capri.activity;

import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.RecyclerView;

import com.capri.R;
import com.capri.adapter.SimpleServiceInfoAdapter;
import com.capri.base.BaseActivity;
import com.capri.model.Action.CallAction;
import com.capri.model.Action.OrderStatusAction;
import com.capri.model.INurse;
import com.capri.model.bean.BaseResultBean;
import com.capri.model.bean.OrderNumBean;
import com.capri.model.bean.TodayOrderBean;
import com.capri.model.impl.NurseModel;
import com.capri.utils.CommonSubscriber;
import com.capri.utils.PreferenceUtils;
import com.capri.widget.PagerGridLayoutManager;
import com.capri.widget.PagerGridSnapHelper;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;
import es.dmoral.toasty.Toasty;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class MainActivity extends BaseActivity {

    @BindView(R.id.tv_nearby_time)
    TextView tvNearbyTime;
    @BindView(R.id.tv_today_deal_num)
    TextView tvTodayDealNum;
    @BindView(R.id.layout_top_simple_info)
    RelativeLayout layoutTopSimpleInfo;
    @BindView(R.id.tv_waiting_confirm)
    TextView tvWaitingConfirm;
    @BindView(R.id.layout_waiting_confirm)
    RelativeLayout layoutWaitingConfirm;
    @BindView(R.id.tv_waiting_go)
    TextView tvWaitingGo;
    @BindView(R.id.layout_waiting_go)
    RelativeLayout layoutWaitingGo;
    @BindView(R.id.tv_serving)
    TextView tvServing;
    @BindView(R.id.layout_serving)
    RelativeLayout layoutServing;
    @BindView(R.id.tv_waiting_confirm2)
    TextView tvWaitingConfirm2;
    @BindView(R.id.layout_waiting_confirm2)
    RelativeLayout layoutWaitingConfirm2;
    @BindView(R.id.recycler_view_deal)
    RecyclerView recycler_view_deal;
    @BindView(R.id.imv_personal)
    ImageView imv_personal;
    @BindView(R.id.layout_empty_order)
    RelativeLayout layout_empty_order;


    private INurse model;
    private SimpleServiceInfoAdapter adapter;
    PagerGridLayoutManager layoutManager;
    private TodayOrderBean todayOrder;

    @Override
    public int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public void setupView() {
        model = new NurseModel();
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        refreshCount();
    }

    @Override
    public void setupData() {
        layoutManager = new PagerGridLayoutManager(
                1, 1, PagerGridLayoutManager.HORIZONTAL);
        layoutManager.setAllowContinuousScroll(false);
        layoutManager.setPageListener(new PagerGridLayoutManager.PageListener() {
            @Override
            public void onPageSizeChanged(int pageSize) {
                Logger.i("onPageSizeChanged-->" + pageSize);
            }

            @Override
            public void onPageSelect(int pageIndex) {
                Logger.i("onPageSelect-->" + pageIndex);
            }
        });
        recycler_view_deal.setLayoutManager(layoutManager);
        PagerGridSnapHelper pageSnapHelper = new PagerGridSnapHelper();
        pageSnapHelper.attachToRecyclerView(recycler_view_deal);
        adapter = new SimpleServiceInfoAdapter(this);
        recycler_view_deal.setAdapter(adapter);
    }

    @OnClick({R.id.layout_waiting_confirm, R.id.layout_waiting_go, R.id.layout_serving, R.id.layout_waiting_confirm2, R.id.imv_personal})
    public void Onlicks(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.layout_waiting_confirm:
            case R.id.layout_waiting_go:
            case R.id.layout_serving:
            case R.id.layout_waiting_confirm2:
                Intent intent = new Intent(MainActivity.this, AllOrdersActivity.class);
                startActivity(intent);
                break;
            case R.id.imv_personal:
                Intent intent1 = new Intent(MainActivity.this, ModifyPasswordActivity.class);
                startActivity(intent1);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshOrder();
    }

    private void refreshOrder() {
        model.GetTodayOrder().doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showDialog();
            }
        }).subscribe(new CommonSubscriber<TodayOrderBean>() {
            @Override
            public void onSuccess(TodayOrderBean response) {
                todayOrder=response;
                hideDialog();
                PreferenceUtils.SaveTodayOrders(response);
                tvWaitingConfirm.setText(response.getWaitConfirmCount() + "");
                tvWaitingGo.setText(response.getWaitStartOffCount() + "");
                tvServing.setText(response.getStartServiceOrderCount() + "");
                tvWaitingConfirm2.setText(response.getAllOrderCount() + "");
                if (response.getList().size() == 0) {
                    layout_empty_order.setVisibility(View.VISIBLE);
                    recycler_view_deal.setVisibility(View.GONE);
                    tvTodayDealNum.setText("今日订单数 "+response.getList().size());
                    tvNearbyTime.setVisibility(View.INVISIBLE);
                } else {
                    tvNearbyTime.setVisibility(View.VISIBLE);
                    layout_empty_order.setVisibility(View.GONE);
                    recycler_view_deal.setVisibility(View.VISIBLE);
                    adapter.setDatas(response.getList());
                    tvNearbyTime.setText("最近订单开始时间  "+response.getList().get(0).getServiceDate());
                    tvTodayDealNum.setText("今日订单数 "+response.getList().size());
                }
            }

            @Override
            public void onFailure(BaseResultBean response) {
                todayOrder=null;
                hideDialog();
                Toasty.error(MainActivity.this, response.getMsg(), Toast.LENGTH_SHORT, true).show();
            }
        });
    }

    private void refreshCount() {
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .map(new Func1<Long, Long>() {
                    @Override
                    public Long call(Long aLong) {
                        return aLong + 1;
                    }
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Long>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(Long aLong) {
                        if(todayOrder!=null){
                            adapter.setDatas(todayOrder.getList());
                        }
                    }
                });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CallAction action) {
        new SweetAlertDialog(this)
                .setTitleText("提示")
                .setContentText("是否给患者打电话")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sweetAlertDialog) {
                        Intent intent = new Intent(Intent.ACTION_DIAL);
                        Uri data = Uri.parse("tel:" + action.getPhoneNum());
                        intent.setData(data);
                        startActivity(intent);
                        sweetAlertDialog.dismissWithAnimation();
                    }
                })
                .show();
    }

    @Subscribe
    public void onEvent(OrderStatusAction orderStatus) {
        model.UpdateOrderStatus(orderStatus.getOrderId(), orderStatus.getStatus()).subscribe(new CommonSubscriber<BaseResultBean>() {
            @Override
            public void onSuccess(BaseResultBean response) {
                refreshOrder();
            }

            @Override
            public void onFailure(BaseResultBean response) {
                Toasty.error(MainActivity.this, response.getMsg(), Toast.LENGTH_SHORT, true).show();
            }
        });
    }

}
